package com.g2.admin.common.ext;

import com.g2.admin.common.constant.Constants;
import com.g2.admin.common.constant.RedisConstants;
import com.g2.admin.model.to.ResultTo;
import com.g2.admin.utils.RedisUtil;
import com.g2.admin.utils.RegularUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

@Component
@Slf4j
public class AuthIntercept implements HandlerInterceptor {
    @Autowired
    RedisUtil<String> redisUtil;
    @Autowired
    RedisUtil<Pattern> patternRedisUtil;
    private static List<String> EXCLUDE_PATH = Lists.newArrayList("/login", "/logout");
    // TODO 排除的URL 可以采用正则表达式的方式排出

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 判断TOKEN是否存在
        String token = request.getHeader(Constants.TOKEN_HEADER);
//        if (!checkToken(response, token)) {
//            return false;
//        }
        String requestUri = request.getRequestURI();
//        if (!checkAuth(requestUri, token)) {
//            return false;
//        }

        return true;
    }

    /**
     * 验证是否授权
     *
     * @param token
     * @return
     */
    private boolean checkAuth(String uri, String token) {
        // 判断权限，如果路径在权限正则表达式里，则通过
        Set<Pattern> patternSet = patternRedisUtil.members(RedisConstants.getKeyAuthPath(token));
        boolean authRs = false;
        for (Pattern pattern : patternSet) {
            if (RegularUtil.matcher(pattern, uri)) {
                authRs = true;
                break;
            }
        }
        return authRs;
    }

    /**
     * 验证Token是否有效
     *
     * @param token
     * @return
     */
    private boolean checkToken(HttpServletResponse response, String token) {
        boolean rs = redisUtil.hasKey(RedisConstants.getKeyToken(token));
        if (rs) {
            return true;
        }
        PrintWriter writer = null;
        try {
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
            writer.write("{\"code\":" + ResultTo.ResultCode.AUTH_FAIL.getCode() + ",\"msg\":\"未授权操作\"}");
            writer.flush();
        } catch (IOException e) {
            log.error("response write err", e);
        } finally {
            if (null != writer) {
                writer.close();
            }
        }
        return false;
    }
}
